// pages/goods_list/index.js
import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
      }
    ],
    goodsList: []
  },

  //接口参数
  queryParams: {
    query: "",
    cid: "",
    pagenum: 1,
    pagesize: 10
  },

  //总页数
  totalPages: 1,

  //点击选择切换tab项
  handleTabsItem(e){
    // console.log(e);
    const { index } = e.detail;
    let { tabs } = this.data;
    tabs.forEach((el, i) => {
      i === index ? el.isActive = true : el.isActive = false;
    });
    this.setData({
      tabs
    });
  },

  //获取商品列表数据
  getGoodsList(){
    request({url: "/goods/search", data: this.queryParams})
    .then(res => {
      console.log(res);
      const total = res.data.message.total;
      this.totalPages = Math.ceil(total/this.queryParams.pagesize);
      this.setData({
        goodsList: [...this.data.goodsList, ...res.data.message.goods]
      });
      //关闭下拉刷新动画
      wx.stopPullDownRefresh();
    })
    .catch(err => {console.log(err)});
  },

  //触底加载下一页
  onReachBottom(){
    // console.log("触底了");
    if(this.queryParams.pagenum >= this.totalPages){
      // console.log("没有下一页了");
      wx.showToast({title: '没有更多了~'});
    }else{
      // console.log("正在加载下一页了");
      this.queryParams.pagenum++;
      this.getGoodsList();
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.queryParams.cid = options.cid;
    this.getGoodsList(this.queryParams);
  },
  onPullDownRefresh(){
    console.log("正在刷新");
    this.setData({
      goodsList: []
    });
    this.queryParams.pagenum = 1;
    this.getGoodsList();
  }

})